<template>
  <div>
    <el-form ref="form" inline :model="temp" :rules="tempRules">
      <el-row :gutter="10">
        <el-col :span="14">
          <div class="phone-search bottom-margin">
            <div>
              <el-form-item label="来电号码：" prop="phone">
                <el-input v-model="temp.phone" placeholder="请输入来电号码" @keyup.enter.native="onKeyupPhone" />
              </el-form-item>
              <el-form-item>
                <el-button
                  :loading="isSeaching"
                  type="primary"
                  @click="onTelSearch"
                >查询</el-button>
              </el-form-item>
            </div>
            <span
              v-if="callDate"
              class="callTime"
            >来电时间：{{ callDate }} 等待数：{{ callNum }}</span>
          </div>

          <el-card class="bottom-margin card">
            <div slot="header">
              <span>客户信息</span>
              <el-button type="text" class="detailBtn" @click="showForegiftDetail">持瓶详情</el-button>
            </div>
            <div class="client-content">
              <div class="client-row">
                <div class="client-label">客户编号：</div>
                <div class="client-value" :title="clientSelected.csmCode">{{ clientSelected.csmCode }}</div>
              </div>
              <div v-if="clientSelected.groupCode" class="client-row">
                <div class="client-label">客户组：</div>
                <div class="client-value" :title="clientSelected.groupCode">{{ clientSelected.groupCode }}</div>
              </div>
              <div v-if="clientSelected.qrCode" class="client-row">
                <div class="client-label">一户一码：</div>
                <div class="client-value" :title="clientSelected.qrCode">{{ clientSelected.qrCode }}</div>
              </div>
              <div class="client-row">
                <div class="client-label">客户名称：</div>
                <div class="client-value" :title="clientSelected.csmName">{{ clientSelected.csmName }}</div>
              </div>
              <div class="client-row">
                <div class="client-label">开户类型：</div>
                <div class="client-value" :title="formatColumnMap(newTypeList, 'value', clientSelected.newType, 'desc')">{{ formatColumnMap(newTypeList, "value", clientSelected.newType, "desc") }}</div>
              </div>
              <div class="client-row">
                <div class="client-label">客户类型：</div>
                <div class="client-value" :title="clientSelected.csmType ? clientSelected.csmType == 1 ? '居民' : clientSelected.csmType === 2 ? '非居民' : '' : ''">{{ clientSelected.csmType ? clientSelected.csmType == 1 ? "居民" : clientSelected.csmType === 2 ? "非居民" : "" : "" }}</div>
              </div>
              <div class="client-row">
                <div class="client-label">所属机构：</div>
                <div class="client-value" :title="clientSelected.nearStationName">{{ clientSelected.nearStationName }}</div>
              </div>
              <div class="client-row">
                <div class="client-label">身份证号：</div>
                <div class="client-value" :title="clientSelected.sfzh">{{ clientSelected.sfzh }}</div>
              </div>
              <div v-if="clientSelected.openAccountPhone" class="client-row">
                <div class="client-label">开户电话：</div>
                <div class="client-value" :title="clientSelected.openAccountPhone">{{ clientSelected.openAccountPhone }}</div>
              </div>
              <div v-if="clientSelected.driverName" class="client-row">
                <div class="client-label">绑定司机：</div>
                <div class="client-value" :title="clientSelected.driverName">{{ clientSelected.driverName }}</div>
              </div>
              <div v-if="clientSelected.dutyName" class="client-row">
                <div class="client-label">值班人：</div>
                <div class="client-value" :title="clientSelected.dutyName">{{ clientSelected.dutyName }}</div>
              </div>
              <div v-if="shippingAddress.preferentialPackageId" class="client-row">
                <div class="client-label2">剩余优惠瓶数：</div>
                <div :class="shippingAddress.preferentialCount ? 'client-value link' : 'client-value red'" @click="showPreferentialDialog">{{ shippingAddress.preferentialCount }}</div>
              </div>
            </div>
            <div v-if="recheckbill">
              <div class="client-value red" @click="showPreferentialDialog">该用户存在隐患尚未整改,请立即复检核查，目前无法购气</div>
            </div>
          </el-card>
          <el-card class="card bottom-margin">
            <div slot="header">
              <span>配送信息</span>
            </div>
            <el-row :gutter="10" class="shipping-address">
              <el-col :span="12">
                <el-table :height="150" :data="shippingInfoData">
                  <el-table-column label="选择" width="50">
                    <template slot-scope="scope">
                      <el-radio
                        v-model="scope.row.select"
                        class="select-radio"
                        :label="true"
                        @change="shippingInfoChange(scope.row)"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column prop="contact" label="联系人" />
                  <el-table-column prop="csmPhone" label="联系电话" width="120" />
                  <el-table-column prop="" label="操作" width="50">
                    <template slot-scope="scope">
                      <el-button
                        type="text"
                        size="small"
                        @click="doDelete(scope.row,1)"
                      >删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
              <el-col :span="12">
                <el-table :height="150" :data="shippingAddressData">
                  <el-table-column label="选择" width="50">
                    <template slot-scope="scope">
                      <el-radio
                        v-model="scope.row.select"
                        class="select-radio"
                        :label="true"
                        @change="shippingAddressChange(scope.row)"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column prop="csmAddressText" label="联系地址" />
                  <el-table-column prop="" label="操作" width="50">
                    <template slot-scope="scope">
                      <el-button
                        v-if="!clientSelected.qrCode && scope.row.sp1 !== 2"
                        type="text"
                        size="small"
                        @click="doDelete(scope.row,2)"
                      >删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
            </el-row>
          </el-card>
          <el-card class="card bottom-margin">
            <div slot="header">
              <span>配送和转派机构</span>
            </div>
            <div class="shipping">
              <div>
                <el-row>
                  <el-col :span="12">
                    <el-form-item
                      label="联系人:"
                      label-width="85px"
                      prop="contactName"
                      class="col-input-full"
                    >
                      <el-input
                        v-model="temp.contactName"
                        maxlength="15"
                        placeholder="请输入联系人"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item
                      label="联系电话:"
                      label-width="85px"
                      prop="telephone"
                      class="redlabel col-input-full"
                    >
                      <el-input
                        v-model="temp.telephone"
                        maxlength="15"
                        placeholder="请输入联系电话"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item
                      label="所在区域:"
                      prop="area"
                      label-width="85px"
                      class="costormLabel redlabel"
                    >
                      <el-select
                        v-model="temp.province"
                        placeholder="请选择省"
                        @change="provinceChange"
                      >
                        <el-option
                          v-for="item in provinceList"
                          :key="item.value"
                          :label="item.areaName"
                          :value="item.areaCode"
                        />
                      </el-select>
                      <el-select
                        v-model="temp.city"
                        placeholder="请选择市"
                        @change="cityChange"
                      >
                        <el-option
                          v-for="item in cityList"
                          :key="item.value"
                          :label="item.areaName"
                          :value="item.areaCode"
                        />
                      </el-select>
                      <el-select
                        v-model="temp.area"
                        placeholder="请选择区"
                        @change="areaChange"
                      >
                        <el-option
                          v-for="item in areaList"
                          :key="item.value"
                          :label="item.areaName"
                          :value="item.areaCode"
                        />
                      </el-select>
                      <el-select v-model="temp.street" placeholder="请选择街道" @change="streetChange">
                        <el-option
                          v-for="item in streetList"
                          :key="item.value"
                          :label="item.areaName"
                          :value="item.areaCode"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item
                      label="联系地址:"
                      label-width="85px"
                      prop="address"
                      class="col-input-full concat-address"
                    >
                      <!-- <el-input
                    v-model="temp.address"
                    maxlength="50"
                    placeholder="请输入联系地址"
                  /> -->

                      <el-autocomplete
                        ref="suggestionInput"
                        v-model="temp.address"
                        v-scrollLoad="getLoad"
                        :maxlength="50"
                        :debounce="300"
                        popper-class="address-autocomplete"
                        :fetch-suggestions="queryAddressSearch"
                        placeholder="请输入联系地址"
                        :trigger-on-focus="false"
                        @select="handleSelect"
                      >
                        <template slot-scope="{ item }">
                          <div class="name">{{ item.value }}</div>
                          <span class="addr">{{ item.address }}</span>
                        </template>
                      </el-autocomplete>
                      <el-button type="primary" icon="el-icon-location-information" @click="addressConfirm" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <div v-if="showConfirmTip && temp.address" class="confirm-tip">该用户的配送地址大于5公里，将会产生配送费用，若要修改请重新选择联系地址</div>
                <div v-if="distanceInfo" class="confirm-distance">最近配送机构:<span>{{ distanceInfo }}</span></div>
                <el-row>
                  <el-col :span="12">
                    <el-form-item
                      label="门牌号:"
                      label-width="85px"
                      prop="doorplate"
                      class="col-input-full"
                    >
                      <el-input
                        v-model="temp.doorplate"
                        maxlength="50"
                        placeholder="请输入门牌号"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item
                      label="楼层:"
                      label-width="50px"
                      prop="floor"
                      class="col-input-full  doorplate-floor"
                    >
                      <el-input
                        v-model="temp.floor"
                        type="number"
                        label="label"
                        class="floor"
                        placeholder="请输入楼层"
                        @blur="floorChange"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row v-if="tabLabel!=='投诉'">
                  <el-col :span="12">
                    <el-form-item
                      label="责任机构:"
                      prop="orgId"
                      label-width="85px"
                      class="col-input-full"
                    >
                      <el-select
                        v-model="temp.orgId"
                        :disabled="isOrgDisabled"
                        placeholder="请选择责任机构"
                        :loading="orgSelectLoading"
                        @change="shopChange"
                      >
                        <el-option
                          v-for="item in shopList"
                          :key="item.value"
                          :label="item.orgName"
                          :value="item.orgId"
                          :disabled="item.disabled"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item
                      label="处理人:"
                      prop="userId"
                      class="col-input-full doorplate-floor"
                    >
                      <el-select v-model="temp.userId" :disabled="isUserDisabled" placeholder="请选择处理人" clearable filterable @change="handerChange">
                        <el-option
                          v-for="item in handlerList"
                          :key="item.value"
                          :label="item.userName"
                          :value="item.userId"
                          :disabled="item.disabled"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <div v-show="monthlyBillEndDt" style="font-size: 14px; color: red;">{{ monthlyBillTips1 }}</div>
                </el-row>
                <div class="saveClient">
                  <el-button type="primary" @click="saveClient">保存客户</el-button>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="10">
          <el-card class="card  bottom-margin">
            <div slot="header">
              <span>快速查询</span>
            </div>
            <div style="display: flex;">
              <el-form-item
                class="conditionType"
                label="条件类型："
                prop="type"
                label-width="90px"
              >
                <el-input
                  v-model="temp.txt"
                  class="condition-input"
                  clearable
                  placeholder="请输入内容，回车键查询"
                  @keyup.enter.native="onKeyupType"
                >
                  <el-select
                    slot="prepend"
                    v-model="conditionType"
                    class="type-selecte"
                    placeholder="请选择条件类型"
                    @change="typeChange"
                  >
                    <el-option
                      v-for="ele in typeList"
                      :key="ele.value"
                      :label="ele.label"
                      :value="ele.value"
                    />
                  </el-select>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  :loading="isFastSearch"
                  @click="fastSearch"
                >快速查找</el-button>
              </el-form-item>
            </div>
            <span class="tips">结果信息栏--仅显示前50条</span>
            <el-table :height="405" :data="clientData.data">
              <el-table-column prop="csmCode" label="编号" width="110" />
              <el-table-column label="选择" width="50">
                <template slot-scope="scope">
                  <!-- <el-checkbox v-model="scope.row.select" @change="clientChange(scope.row)" /> -->
                  <el-radio
                    v-model="scope.row.select"
                    class="select-radio"
                    :label="true"
                    @change="clientChange(scope.row)"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="address" label="客户信息">
                <template slot-scope="scope">
                  <div>
                    <span>身份证:</span><span>{{ scope.row.sfzh }}({{ scope.row.csmTypeText }})</span>
                  </div>
                  <div>
                    <span>电话:</span><span>{{ scope.row.csmRgPhone }}({{ scope.row.csmName }})</span>
                  </div>
                  <div>
                    <span>编号:</span><span>{{ scope.row.csmCode }}</span>
                  </div>
                  <div>
                    <span>所属机构:</span><span>{{ scope.row.nearStationName }}</span>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          <!-- <el-pagination
              :current-page="clientData.currentPage"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="clientData.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="clientData.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            /> -->
          </el-card>
          <el-card class="card  bottom-margin">
            <el-tabs v-model="record" type="card" @tab-click="handleClick">
              <el-tab-pane label="购气记录" name="1">
                <el-table v-loading="$loadingPlugin.getRecentOrderList" :height="282" :data="purchaseHistory">
                  <el-table-column prop="orderCode" label="订单号" min-width="90" show-overflow-tooltip>
                    <template slot-scope="scope">
                      <div class="order-code" @click="circulationInfo(scope.row)">{{ scope.row.orderCode }}</div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="goodsCount" label="数量" min-width="50" show-overflow-tooltip />
                  <el-table-column prop="goodsDesc" label="商品描述" min-width="150" show-overflow-tooltip />
                  <el-table-column prop="transactTimeText" label="下单时间" min-width="120" show-overflow-tooltip />
                  <el-table-column prop="appointmentTime" label="预约时间" min-width="190" show-overflow-tooltip />
                  <el-table-column prop="fromPlatDesc" label="来源" min-width="80" show-overflow-tooltip />
                  <el-table-column prop="orderStatusDesc" label="状态" min-width="80" show-overflow-tooltip />
                  <!-- <el-table-column prop="decimalSpare1" label="远距配送费" min-width="80" show-overflow-tooltip /> -->
                  <el-table-column prop="" label="操作" fixed="right" width="50">
                    <template slot-scope="scope">
                      <el-button
                        v-show="scope.row.orderStatus===2||scope.row.orderStatus===5"
                        type="text"
                        size="small"
                        @click="openPressOrder(scope.row)"
                      >催单</el-button>
                      <!-- <el-button
                        v-show="scope.row.isReservation===1&&(scope.row.orderStatus===2||scope.row.orderStatus===1)"
                        v-permission="1"
                        type="text"
                        size="small"
                        @click="changeAppointmentDt(scope.row)"
                      >修改</el-button> -->
                    </template>
                  </el-table-column>
                </el-table>
              </el-tab-pane>
              <el-tab-pane label="投诉记录" name="2">
                <el-table :height="165" :data="complainTableData">
                  <el-table-column prop="createTime" label="登记时间" min-width="140" show-overflow-tooltip />
                  <el-table-column prop="createUser" label="登记人" min-width="90" show-overflow-tooltip />
                  <el-table-column prop="complainContent" label="投诉内容" min-width="170" show-overflow-tooltip />
                  <el-table-column prop="remark" label="备注" min-width="120" show-overflow-tooltip />
                  <el-table-column prop="statusName" label="状态" min-width="100" show-overflow-tooltip />
                  <el-table-column label="催单" min-width="80" show-overflow-tooltip>
                    <template slot-scope="{row}">
                      <el-button v-if="row.statusName === '未处理'" type="text" class="btnText" @click="handleReminder(row)">催单</el-button>
                      <span v-else>催单</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="退单" min-width="80" show-overflow-tooltip>
                    <template slot-scope="{row}">
                      <el-button v-if="row.statusName === '未处理'" type="text" class="btnText" @click="handleChargeback(row)">退单</el-button>
                      <span v-else>退单</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="流转" min-width="90" show-overflow-tooltip>
                    <template slot-scope="{row}">
                      <el-button type="text" class="btnText" @click="handleExchange(row)">流转</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-tab-pane>
            </el-tabs>

          </el-card>
        </el-col>
      </el-row>

      <el-tabs ref="optionTab" v-model="tabLabel" class="option-tab" :tab-position="'left'" type="card" :class="currentName=='买气'?'option-tab-show':''" @tab-click="tabChange">
        <el-tab-pane label="买气" name="买气">
          <placeAnOrder
            ref="placeAnOrder"
            :current-phone-data="currentPhoneData"
            :purchase-history="purchaseHistory"
            :currentuser-info="currentuserInfo"
            :old-address="oldAddress"
            :old-phone-list="oldPhoneList"
            :shipping-info-selected="shippingInfoSelected"
            :temp="temp"
            :client-selected="clientSelected"
            :shop-list="shopList"
            :deposit-order-data="depositOrderData"
            :last-order-detail="lastOrderDetail"
            :main-goods-prices="mainGoodsPrices"
            :floorfee-list="FloorfeeList"
            :serve-price-list="ServePriceList"
            :old-custom-info="oldCustomInfo"
            :appointment-info="orgInfo"
            :deposit-details-info="depositDetailsInfo"
            @onSubmit="onSubmit"
            @validateForm="validateForm"
            @goodTypeChange="goodTypeChange"
            @goodsChange="goodsChange"
            @confirmDistance="confirmDistance"
          />
        </el-tab-pane>
        <el-tab-pane label="报修" name="报修">
          <callRepair ref="callRepair" :temp="temp" :user-data="userData" :current-phone-data="currentPhoneData" @onSubmit="onSubmit" />
        </el-tab-pane>
        <el-tab-pane label="投诉" name="投诉">
          <callComplaint ref="callComplaint" :client-selected="clientSelected" :shipping-info-selected="shippingInfoSelected" :temp="temp" :user-data="userData" :current-phone-data="currentPhoneData" @onSubmit="onSubmit" />
        </el-tab-pane>
        <el-tab-pane label="退瓶" name="退瓶">
          <returnBottle ref="returnBottle" :temp="temp" :user-data="userData" @onSubmit="onSubmit" />
        </el-tab-pane>
        <el-tab-pane label="其他" name="其他">
          <callOther ref="callOther" />
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <circulation ref="circulation" />
    <geolocation ref="geolocation" />
    <location ref="location" />
    <foregiftDetail
      ref="foregiftDetail"
      :dialog="dialogData"
    />
    <order-details
      ref="orderDetails"
      :payment-method-map="paymentMethodMap"
      :pay-status-map="payStatusMap"
      :transactor-list="transactorList"
      :order-flag-map="orderFlagMap"
      :order-source-map="orderSourceMap"
      :order-status-map="orderStatusMap"
    />
    <press-order ref="pressOrder" />
    <change-appointmentDt ref="changeAppointmentDt" :parent-fetch-data="refresh" />

    <reminderDialog ref="reminderDialog" :client-selected="clientSelected" />
    <chargebackDialog ref="chargebackDialog" type="complain" @chargebackSubmit="chargebackSubmit" />
    <exchangeDialog ref="exchangeDialog" :client-selected="clientSelected" />
    <confirmClasses ref="confirmClasses" />
    <showPreferential ref="showPreferential" />
  </div>
</template>

<script>
  import {
    deleteAddressByParam,
    deletePhoneByParam,
    queryCustomersInfo,
    findRecentOrderList,
    // findUserList,
    csDeliverUserList,
    phoneOrderDistance,
    queryAddressList,
    queryPhoneList,
    selectAreaCode,
    usage,
    queryUserByOrgId,
    searchCustomerdeposit,
    phoneOrderSearchLastOrder,
    phoneOrderGoodsPrices,
    phoneOrderFloorfee,
    phoneOrderServePrice,
    queryTransactorList,
    queryMap,
    phoneOrderSaveUser,
    phoneOrderSearchCms,
    confirmLonLat,
    queryInfoPhone,
    complainTop,
    getComplainStatus,
    orderDutyCheck,
    orderbillCanUrge,
    recheckbillCheck,
    findShopDistanceList,
    getDepositOrderInfoApi,
    getNearestStationInfoApi
  } from '@/api'
  import { mapGetters } from 'vuex'
  import placeAnOrder from './placeAnOrder'
  import { getLocalSearch } from '@/utils/BMap'
  import store from '@/store'
  import circulation from './circulation'
  import callRepair from './repair'
  import callComplaint from './complaint'
  import callOther from './other'
  import dayjs from 'dayjs'
  import geolocation from './geolocation.vue'
  import Location from '../../customerManage/components/Location.vue'
  import foregiftDetail from './foregiftDetail.vue'
  import returnBottle from './returnBottle'
  import orderDetails from '../../../orderCenter/orderManage/components/OrderDetails.vue'
  import PressOrder from '../../../components/PressOrderModal'
  import ChangeAppointmentDt from '../../../components/ChangeAppointmentDt'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { formatColumnMap, parseTime } from '@/utils'
  import reminderDialog from './reminderDialog.vue'
  import chargebackDialog from './chargebackDialog.vue'
  import exchangeDialog from './exchangeDialog.vue'
  import showPreferential from './showPreferential'
  import confirmClasses from '@/views/components/ConfirmClasses'

  export default {
    name: 'call-order-add',
    components: {
      placeAnOrder,
      circulation,
      callRepair,
      callComplaint,
      callOther,
      geolocation,
      foregiftDetail,
      orderDetails,
      Location,
      returnBottle,
      PressOrder,
      ChangeAppointmentDt,
      reminderDialog, chargebackDialog, exchangeDialog,
      confirmClasses,
      showPreferential
    },
    directives: {
      scrollLoad: {
        bind(el, binding, vnode) {
          const wrapDom = el.querySelector('.el-autocomplete-suggestion__wrap')
          const listDom = el.querySelector('.el-autocomplete-suggestion__list')
          wrapDom.addEventListener(
            'scroll',
            e => {
              const condition =
                listDom.offsetHeight -
                wrapDom.offsetHeight +
                37 -
                0.3 -
                wrapDom.scrollTop
              if (condition < 0 && !vnode.context.loading) {
                // 滚动到底部则执行滚动方法load，binding.value就是v-scrollLoad绑定的值，加()表示执行绑定的方法
                binding.value()
              }
            },
            false
          )
        }
      }
    },
    props: {
      currentPhoneData: {
        type: Object,
        default: () => { return {} }
      },
      callDate: {
        type: String,
        default: '',
        required: false
      },
      callNum: {
        type: Number,
        default: 0,
        required: false
      },
      editableTabsValue: {
        type: String || Number,
        default: '',
        required: false
      }
    },
    data() {
      const validMobile = (rule, value, callback) => {
        const reg = /^1[3456789]\d{9}$/
        const tel = /^((0\d{2,3})-)?(\d{7,8})$/
        if (!value) {
          callback(new Error('请输入联系方式'))
        } else if (value && !(reg.test(value) || tel.test(value))) {
          callback(new Error('请输入正确的联系方式'))
        } else {
          callback()
        }
      }
      return {
        temp: {
          phone: '',
          csmRgPhone: undefined,
          sfzh: undefined,
          csmName: undefined,
          csmCode: undefined,
          cardNo: undefined,
          openAccountPhone: undefined,
          contactName: '',
          telephone: '',
          oldAddress: '',
          address: '',
          doorplate: '',
          floor: '',
          orgId: '',
          userId: '',
          latitude: '',
          longitude: '',
          provinceName: '',
          cityName: '',
          countryName: '',
          area: '',
          streetName: '',
          gTypeId: '',
          goods: '',
          specCode: '',
          description: [],
          remark: '',
          distance: 0,
          txt: ''
        },
        oldCustomInfo: {},
        tempRules: {
          contactName: [
            { required: true, message: '联系人不能为空', trigger: 'change' }
          ],
          telephone: [{ validator: validMobile, trigger: 'change' }],
          address: [
            { required: true, message: '联系地址不能为空', trigger: 'change' }
          ],
          orgId: [
            { required: true, message: '请选择责任机构', trigger: 'change' }
          ],
          userId: [{ required: false, message: '请选择处理人', trigger: 'change' }],
          paymentMethod: [
            { required: true, message: '请选择支付方式', trigger: 'change' }
          ],
          doorplate: [{ required: true, message: '门牌号不能为空', trigger: 'change' }],
          floor: [{ required: true, message: '楼层不能为空', trigger: 'change' }]
        },
        typeList: [
          {
            label: '电话号码',
            value: 1
          },
          {
            label: '身份证',
            value: 2
          },
          {
            label: '客户名称',
            value: 3
          },
          {
            label: '客户编号',
            value: 4
          },
          {
            label: '充值卡',
            value: 5
          },
          {
            label: '开户电话',
            value: 6
          }
        ],
        newTypeList: [
          {
            value: 1,
            desc: '自购瓶'
          },
          {
            value: 2,
            desc: '租用瓶'
          },
          {
            value: 3,
            desc: '借用瓶'
          },
          {
            value: 4,
            desc: '携瓶'
          }
        ],
        conditionType: 4,
        typeVal: ['csmRgPhone', 'sfzh', 'csmName', 'csmCode', 'cardNo', 'openAccountPhone'],
        clientData: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
          data: []
        },
        clientSelected: {},
        shippingInfoData: [],
        shippingAddressData: [],
        shippingInfoSelected: {},
        shippingPhone: {},
        shippingAddress: {},
        provinceList: [],
        cityList: [],
        areaList: [],
        streetList: [],
        commodityData: [],
        slectAddress: {},
        addressInfo: {
          page_num: 0,
          page_size: 10
        },
        suggestionCb: undefined,
        suggestionList: [],
        shopList: [],
        handlerList: [],
        goodTypeList: [],
        goodsList: [],
        purchaseHistory: [],
        oldAddress: [],
        oldPhoneList: [],
        currentuserInfo: {},
        isSeaching: false,
        isFastSearch: false,
        dialogData: {},
        showConfirmTip: false,
        distanceInfo: '',
        userData: {},
        tabLabel: '买气',
        depositOrderData: [],
        lastOrderDetail: null,
        mainGoodsPrices: [], // 主营商品价格
        ServePriceList: [], // 服务费
        FloorfeeList: [], // 上楼费
        paymentMethodMap: [],
        payStatusMap: [],
        orderSourceMap: [],
        orderFlagMap: [],
        orderStatusMap: [],
        transactorList: [],
        orgInfo: {},
        monthlyBillEndDt: '',
        monthlyBillTips1: '',
        monthlyBillTips2: '',
        record: '1',
        complainTableData: [],
        complainStatus: [],
        recheckbill: false,
        depositDetailsInfo: {},
        orgSelectLoading: false
      }
    },
    computed: {
      ...mapGetters([
        'orgList',
        'corpSettingData',
        'csmCodeForPayOrder'
      ]),
      isUserDisabled: function() {
        if (this.tabLabel === '报修') {
          const i = this.shopList.find(item => item.orgId === this.temp.orgId)

          return i && (i.sp1 >> 14 & 0x01) === 1
        } else {
          return false
        }
      },
      currentName: function() {
        return this.tabLabel
      },
      isFirstDepositOrder() {
        return this.depositDetailsInfo.depositDetails ? !!this.depositDetailsInfo.depositDetails.length : false
      },
      isOrgDisabled: function() {
        return (this.tabLabel === '报修' && (this.corpSettingData.sp6 >> 19 & 0x01) === 0x01) || (this.tabLabel === '买气' && this.isFirstDepositOrder)
      }
    },
    watch: {
      'temp.orgId': {
        handler(newVal, oldVal) {
          const box = this.shopList.filter((item) => {
            return item.orgId === this.temp.orgId
          })
          this.orgInfo = box[0]
        },
        deep: true,
        immediate: true
      },
      'monthlyBillEndDt': {
        handler(newVal, oldVal) {
          if (newVal) {
            const diff = dayjs(new Date()).diff(dayjs(newVal), 'days')
            this.monthlyBillTips1 = `月结客户(超过${diff}天未结清)`
            this.monthlyBillTips2 = `提示：该客户有月结单超过${diff}天未结清`
          }
        },
        deep: true,
        immediate: true
      },
      'csmCodeForPayOrder': {
        handler(val) {
          if (val) {
            this.$nextTick(() => {
              this.conditionType = 4
              this.temp.txt = val
              this.fastSearch()
              this.$store.dispatch('payOrder/setCsmCodeForPayOrder', '')
            })
          }
        },
        immediate: true
      }
    },
    created() {
      this.getProvinceData()
      this.getData()
      this.getGoodsPrices()
      this.GetFloorfee({})
      this.GetServePrice()
      this.queryOptionsMap()
      this.getTransactorList()
    },
    methods: {
      formatColumnMap,
      // 当前用户若首单存在押金单回显押金单信息，不可编辑
      async getFirstDepositOrderInfo() {
        const params = {
          csmId: this.clientSelected.csmId
        }
        const res = await getDepositOrderInfoApi(params)
        if (res.data) {
          this.depositDetailsInfo = res.data
        }
      },
      async getNearestStationInfo() {
        this.orgSelectLoading = true
        const res = await getNearestStationInfoApi({
          latitude: this.temp.latitude,
          longitude: this.temp.longitude
        })
        this.orgSelectLoading = false
        if (res.data) {
          // const { orgId, orgSNNo } = res.data
          return res.data
        }
      },
      getData() {
        const currentPhone = this.currentPhoneData.title
        if (currentPhone && currentPhone === this.editableTabsValue) {
          this.temp.phone = currentPhone
          this.onTelSearch()
        }
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2, res3, res4, res5, res6, res7] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'OrderStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderFlag' }),
          mergeAsyncFunc(queryMap, { enumName: 'CustomerType' }),
          mergeAsyncFunc(queryMap, { enumName: 'PayStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' }),
          mergeAsyncFunc(queryMap, { enumName: 'ReStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderSource' })
        ])
        this.orderStatusMap = res1.data.filter((item) => item.value !== 6) // 订单类型(去掉‘已转派’)
        this.orderFlagMap = res2.data // 订单类型
        this.customerTypeMap = res3.data // 客户类型
        this.payStatusMap = res4.data // 支付状态
        this.paymentMethodMap = res5.data.filter(item => item.value === 1 || item.value === 2 || item.value === 16 || item.value === 128 || item.value === 256 || item.value === 2048) // 支付方式
        this.reStatusMap = res6.data // 回执状态
        this.orderSourceMap = res7.data // 订单来源
      },
      // 获取下单人列表
      async getTransactorList() {
        const res = await queryTransactorList({})
        this.transactorList = res.data
      },
      // 监听回车键快捷查询
      onKeyupPhone() {
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          this.onTelSearch()
        }, 500)
      },
      onTelSearch() {
        if (this.temp.phone) {
          this.isSeaching = true
          this.conditionType = 1
          this.temp.txt = this.temp.phone
          this.temp[this.typeVal[this.conditionType - 1]] = this.temp.phone
          this.getClientData()
        }
      },
      // 监听回车键快捷查询
      onKeyupType() {
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          this.fastSearch()
        }, 500)
      },
      // 快速查找
      fastSearch() {
        if (!this.temp.txt) {
          this.$message.error('条件输入框不能为空')
          return
        } else {
          this.temp[this.typeVal[this.conditionType - 1]] = (this.temp.txt).trim()
        }
        this.isFastSearch = true
        this.resetForm()
        this.clearAddressInfo()
        this.getClear()
        this.$refs.placeAnOrder.getRemarkClear()
        this.getClientData()
      },
      typeChange(val) {
        this.typeVal.forEach((item, index) => {
          if (index + 1 !== val) {
            this.temp[item] = undefined
          }
        })
      },
      // 客户信息
      async clientChange(row) {
        this.getClear()
        this.shippingInfoSelected = {}
        this.shippingPhone = {}
        this.shippingAddress = {}
        this.purchaseHistory = []
        this.clientSelected = row
        console.log(this.clientSelected, '-----------')
        this.clientData.data.forEach((item, index) => {
          if (item.csmId !== this.clientSelected.csmId) {
            this.clientData.data[index].select = false
          }
        })
        await this.getFirstDepositOrderInfo()
        this.getRecentOrderList()
        this.searchForPhone()
        if (this.tabLabel === '报修' || this.tabLabel === '投诉') {
          this.queryUserByOrgId()
        }
        if (this.tabLabel === '投诉') {
          this.$refs.callComplaint.reset()
        }
      },
      async searchForPhone() {
        const params = { csmId: this.clientSelected.csmId, phone: '', fromPlat: 7 }
        const res1 = await phoneOrderSearchCms(params)
        this.phoneData = res1.data
        queryInfoPhone({ csmId: this.clientSelected.csmId, phone: this.temp.phone }).then(res => {
          this.clientSelected.qrCode = res.data.qrCode
          this.clientSelected.csmAddressId = res.data.csmAddressId
          this.clientSelected.newType = res.data.newType
          this.clientSelected.subType = res.data.subType
          this.clientSelected.driverName = res.data.driverName ? res.data.driverName : ''
          this.$refs.placeAnOrder.cinfo = res.data
          const list = JSON.parse(JSON.stringify(this.clientData.data))
          this.clientSelected.csmName = res.data.csmName
          this.clientData.data = list
        })
      },
      getClear() {
        this.shopList = []
        this.handlerList = []
        this.temp.orgId = ''
        this.temp.userId = ''
        this.$refs.placeAnOrder.getGoodsClear()
        this.$refs.placeAnOrder.deliveryCostName = '远距配送费'
        this.$refs.placeAnOrder.canUseMonthly = false
      },
      // 客户列表
      async getClientData() {
        this.resetForm()
        const params = {
          pageIndex: this.clientData.currentPage,
          pageSize: 20,
          params: {
            csmRgPhone: this.temp.csmRgPhone,
            sfzh: this.temp.sfzh,
            csmName: this.temp.csmName,
            csmCode: this.temp.csmCode,
            cardNo: this.temp.cardNo,
            openAccountPhone: this.temp.openAccountPhone
          }
        }
        queryCustomersInfo(params).then(res => {
          if (res) {
            if (res.data.length > 0) {
              this.clientData.data = res.data.map(item => ({
                select: false,
                ...item,
                csmTypeText: item.csmType ? item.csmType === 1 ? '居民用户' : item.csmType === 2 ? '非居民用户' : item.csmType === 4 ? '工业用户' : item.csmType === 8 ? '瓶批用户' : item.csmType === 16 ? '槽批用户' : '' : ''
              }))
              this.defalutClientData()
            } else {
              this.isSeaching = false
              this.isFastSearch = false
              this.$message.error('未查找到客户信息')
            }
          } else {
            this.isSeaching = false
            this.isFastSearch = false
          }
        }, err => {
          console.log(err)
          this.isSeaching = false
          this.isFastSearch = false
        })
      },
      // 优惠剩余瓶数详情
      showPreferentialDialog() {
        if (this.shippingAddress.preferentialCount) {
          this.$refs.showPreferential.open(this.shippingAddress, 7)
        }
      },
      // 展示押金详情
      async showForegiftDetail() {
        const params = {
          // corpSN: this.clientSelected.corpSN,
          csmId: this.clientSelected.csmId
        }
        const res = await usage(params)
        if (res && res.data) {
          this.dialogData = res.data
          this.$refs.foregiftDetail.open(this.dialogData)
        }
      },
      async defalutClientData() {
        this.tabLabel = '买气'
        if (this.clientData.data.length > 0) {
          this.clientData.data.forEach((item, index) => {
            if (index === 0) {
              item.select = true
            } else {
              item.select = false
            }
          })
          this.clientSelected = this.clientData.data[0]
          this.temp.isCustomPrice = this.clientSelected.isCustomPrice
        } else {
          this.clientSelected = {}
        }
        if (this.tabLabel === '报修' || this.tabLabel === '投诉') {
          this.queryUserByOrgId()
        }
        this.$refs.callRepair.getRepairTop(this.clientSelected)
        await this.getFirstDepositOrderInfo()
        await this.getRecentOrderList()
        this.complainSearch()
      },
      async queryUserByOrgId() {
        if (this.clientSelected.nearStation) {
          const params = {
            orgId: this.shippingAddress.orgId ? this.shippingAddress.orgId : this.clientSelected.nearStation
            // corpSN: this.clientSelected.corpSN
          }
          const res = await queryUserByOrgId(params)
          this.userData = res.data
          if (this.userData) {
            this.setUserData()
          } else {
            // this.temp.orgId = ''
            this.temp.userName = ''
            this.temp.userId = ''
          }
        }
      },
      // 配送信息
      async getAddressList() {
        await this.getPhoneList()
        await this.getAddressInfoList()
        await this.getFillShippingInfo()
      },
      async getPhoneList() {
        const params = {
          // corpSN: this.clientSelected.corpSN,
          csmId: this.clientSelected.csmId
        }
        const resPhone = await queryPhoneList(params)
        if (resPhone && resPhone.data) {
          const hasIsMain = resPhone.data.findIndex(item => item.isMain)
          let hasRecord = ''
          this.shippingInfoData = resPhone.data.map((item, index) => ({
            index,
            select: false,
            ...item
          }))
          if (this.purchaseHistory.length > 0) {
            hasRecord = resPhone.data.findIndex(item => item.csmPhone === this.purchaseHistory[0].contactPhone)
            if (hasRecord !== -1) {
              this.shippingInfoData[hasRecord].select = true
            } else if (hasIsMain !== -1) {
              this.shippingInfoData[hasIsMain].select = true
            }
          } else if (hasIsMain !== -1) {
            this.shippingInfoData[hasIsMain].select = true
          }
        } else {
          this.isSeaching = false
          this.isFastSearch = false
        }
        if (this.shippingInfoData.length > 0) {
          const itemSelect = this.shippingInfoData.find(item => item.select)
          this.shippingPhone = itemSelect
        } else {
          this.shippingPhone = {}
          this.getClear()
        }
        this.oldPhoneList = JSON.parse(JSON.stringify(this.shippingInfoData))
      },
      async getAddressInfoList() {
        const params = {
          // corpSN: this.clientSelected.corpSN,
          csmId: this.clientSelected.csmId,
          fromPlat: 7 // 话务下单
        }
        const resAddress = await queryAddressList(params)
        if (resAddress && resAddress.data) {
          let hasRecord = ''
          this.shippingAddressData = resAddress.data.map((item, index) => ({
            index,
            select: false,
            ...item,
            csmAddressText: item.csmFloor
              ? item.csmAddress +
                (item.doorplate || '') +
                `(楼层:${item.csmFloor || ''})`
              : item.csmAddress
          }))
          const hasIsMain = resAddress.data.findIndex(item => item.isMain)
          if (this.purchaseHistory.length > 0) {
            hasRecord = this.shippingAddressData.findIndex(item => item.csmAddressId === this.purchaseHistory[0].csmAddressId)
            if (hasRecord !== -1) {
              this.shippingAddressData[hasRecord].select = true
            } else if (hasIsMain !== -1) {
              this.shippingAddressData[hasIsMain].select = true
            }
          } else if (hasIsMain !== -1) {
            this.shippingAddressData[hasIsMain].select = true
          }
        } else {
          this.isSeaching = false
          this.isFastSearch = false
        }
        if (this.shippingAddressData.length > 0) {
          const itemSelect = this.shippingAddressData.find(item => item.select)
          this.temp.isConfirm = itemSelect.isConfirm
          this.shippingAddress = itemSelect
        } else {
          this.shippingAddress = {}
          this.getClear()
        }
        const res = await recheckbillCheck({ csmid: this.clientSelected.csmId })
        this.recheckbill = false
        if (res.data && res.data > 0) {
          this.recheckbill = true
        }

        queryInfoPhone({ csmId: this.clientSelected.csmId, phone: this.temp.phone }).then(res => {
          // 选择配送地址和一户一码的地址不一致时清空一户一码code
          this.clientSelected.csmAddressId = res.data.csmAddressId
          this.clientSelected.newType = res.data.newType
          this.clientSelected.subType = res.data.subType
          this.monthlyBillEndDt = res.data.monthlyBillEndDt
          console.log(res.data.monthlyBillEndDt)
          this.clientSelected.driverName = res.data.driverName
          this.clientSelected.dutyName = res.data.dutyName
          this.$refs.placeAnOrder.cinfo = res.data
          if (this.shippingAddress.csmAddressId === res.data.csmAddressId) {
            this.clientSelected.qrCode = res.data.qrCode
          } else {
            this.qrCode = res.data.qrCode
          }
        })
        this.$refs.callRepair.getRepairTop(this.clientSelected, this.shippingAddress)
        if (this.tabLabel === '退瓶') {
          this.$refs.returnBottle.depositlist(this.clientSelected, this.shippingAddress)
        }
        this.oldAddress = JSON.parse(JSON.stringify(this.shippingAddressData))
      },
      shippingInfoChange(row) {
        this.getClear()
        this.shippingPhone = row
        this.shippingInfoData.forEach((item, index) => {
          if (item.index !== row.index) {
            this.shippingInfoData[index].select = false
          }
        })
        this.getFillShippingInfo()
      },
      async shippingAddressChange(row) {
        // console.log('row', row)
        // console.log(this.clientSelected)
        if (this.clientSelected.csmAddressId !== row.csmAddressId) {
          this.clientSelected.qrCode = ''
        } else {
          this.clientSelected.qrCode = this.qrCode
        }
        this.getClear()
        this.temp.distance = 0
        this.temp.isConfirm = row.isConfirm
        // 选择配送地址和一户一码的地址不一致时清空一户一码code

        if (this.tabLabel === '投诉' || this.tabLabel === '报修') {
          this.temp.orgId = row.orgId
          this.temp.orgName = formatColumnMap(this.shopList, 'orgId', this.temp.orgId, 'orgName')
          this.temp.userId = ''
        }
        this.shippingAddress = row
        this.shippingAddressData.forEach((item, index) => {
          if (item.index !== row.index) {
            this.shippingAddressData[index].select = false
          }
        })
        this.$refs.callRepair.getRepairTop(this.clientSelected, this.shippingAddress)
        if (this.tabLabel === '退瓶') {
          this.$refs.returnBottle.depositlist(this.clientSelected, this.shippingAddress)
        }
        this.getFillShippingInfo()
      },
      // 获取配送和转派机构
      async getFillShippingInfo() {
        this.isSeaching = false
        this.isFastSearch = false
        this.shippingInfoSelected = {
          ...this.shippingAddress,
          ...this.shippingPhone
        }
        // console.log('shippingInfoSelected', this.shippingInfoSelected)
        const {
          contact,
          csmPhone,
          provinceCode,
          cityCode,
          countryCode,
          streetCode,
          csmAddress,
          csmFloor,
          doorplate,
          latitude,
          longitude,
          createTime,
          corpSN,
          csmId,
          orgId,
          orgSNNo,
          orgName
        } = this.shippingInfoSelected
        this.temp.contactName = contact
        this.temp.telephone = csmPhone
        this.temp.province = provinceCode
        this.temp.csmType = this.clientSelected.csmType
        await this.provinceChange()
        this.temp.city = cityCode
        await this.cityChange()
        this.temp.area = countryCode
        await this.areaChange()
        this.temp.street = streetCode
        this.streetChange()
        this.temp.createTime = createTime
        this.temp.floor = csmFloor
        this.temp.address = csmAddress
        this.temp.doorplate = doorplate
        this.temp.latitude = latitude
        this.temp.longitude = longitude
        this.temp.monthlyBillTips2 = this.monthlyBillTips2
        if (this.isFirstDepositOrder) {
          this.temp.orgId = this.depositDetailsInfo.ckOrgId
          this.temp.orgSNNo = this.depositDetailsInfo.ckOrgSNNo
          this.temp.orgName = this.depositDetailsInfo.ckOrgName
        } else if (this.depositDetailsInfo.isDeliver) {
          const { orgId, orgSNNo, orgName } = await this.getNearestStationInfo()
          if (this.temp.orgId !== orgId) {
            this.temp.orgId = orgId
            this.temp.orgSNNo = orgSNNo
            this.temp.orgName = orgName
          }
        } else {
          this.temp.orgId = orgId
          this.temp.orgSNNo = orgSNNo
          this.temp.orgName = orgName
        }
        // if (this.purchaseHistory.length === 0) {
        // this.temp.orgId = orgId
        // this.temp.orgSNNo = orgSNNo
        // this.temp.orgName = orgName
        // } else {
        //   this.temp.orgId = this.purchaseHistory[0] ? this.purchaseHistory[0].orgId || '' : ''
        //   this.temp.orgSNNo = this.purchaseHistory[0] ? this.purchaseHistory[0].orgSNNo || '' : ''
        //   this.temp.orgName = this.purchaseHistory[0] ? this.purchaseHistory[0].orgName || '' : ''
        // }
        await this.getShopList()
        await this.getUserList()
        this.$refs.placeAnOrder.getDefaultGoodsInfo()
        this.$refs.placeAnOrder.getOverage({ corpSN, csmId, csmCode: this.temp.csmCode })
        this.$refs.placeAnOrder.gettimeList()
        this.$refs.placeAnOrder.radio = 1
        this.$refs.placeAnOrder.popoverVisible = false
        this.$refs.placeAnOrder.popoverVisibleDay = false
        if (this.temp.latitude && this.temp.longitude && this.temp.orgId) {
          // this.checkAddress()
        }
        // if (this.temp.latitude && this.temp.longitude && !this.temp.isConfirm) {
        //   this.confirmDistance()
        // }
        if (this.tabLabel === '报修' || this.tabLabel === '投诉') {
          this.queryUserByOrgId()
        }
        if (this.tabLabel === '退瓶') {
          this.temp.orgId = this.clientSelected.nearStation
          this.temp.orgSNNo = formatColumnMap(this.shopList, 'orgId', this.temp.orgId, 'orgSNNo')
        }
        this.getShopDistanceList()
        this.oldCustomInfo = JSON.parse(JSON.stringify(this.temp))
      },
      // 查询客户租瓶信息
      async queryDepositOrder() {
        if (this.temp.orgId && this.clientSelected.csmId) {
          const params = {
            csmId: this.clientSelected.csmId, orgId: this.temp.orgId
          }
          const rlt = await searchCustomerdeposit(params)
          var data = rlt.data || []
          // 订单租瓶信息
          this.depositOrderData = data
        }
      },
      // 查询上次订单
      async searchLastOrder(csmAddressId = '') {
        const params = {
          csmId: this.clientSelected.csmId,
          csmAddressId
        }
        if (params.csmId && csmAddressId) {
          const res = await phoneOrderSearchLastOrder(params)
          if (res.data) {
            this.lastOrderDetail = res.data
          }
        }
      },
      confirmDistance() {
        this.$confirm('您的配送地址未确认，请先确认。', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.addressConfirm()
        })
      },
      async getRecentOrderList() {
        if (!this.clientSelected.csmId) return
        const params = {
          // corpSN: this.clientSelected.corpSN,
          csmId: this.clientSelected.csmId
        }
        findRecentOrderList(params).then(async(res) => {
          if (res && res.data) {
            this.purchaseHistory = res.data.map((item) => ({
              ...item,
              transactTimeText: item.transactTime ? dayjs(item.transactTime).format('YY-MM-DD HH:mm') : '',
              appointmentTime: item.appointmentDt && item.dateTimeSpare1 ? parseTime(item.dateTimeSpare1, '{h}:{i}') === '23:59' ? parseTime(item.appointmentDt, '{y}-{m}-{d}') : parseTime(item.appointmentDt, '{y}-{m}-{d} {h}:{i}') + ' 至 ' + parseTime(item.dateTimeSpare1, '{h}:{i}') : '',
              fromPlatDesc: formatColumnMap(this.orderSourceMap, 'value', item.fromPlat, 'desc'),
              orderStatusDesc: formatColumnMap(this.orderStatusMap, 'value', item.orderStatus, 'desc')
            }))
            await this.getAddressList()
            if (this.purchaseHistory.length > 0) {
              await this.getUserList()
              this.temp.userId = this.purchaseHistory[0] ? this.purchaseHistory[0].ownerId || '' : ''
              this.oldCustomInfo.userId = this.purchaseHistory[0] ? this.purchaseHistory[0].ownerId || '' : ''
              if (this.temp.userId) {
                this.handerChange()
              }
            }
          } else {
            this.isSeaching = false
            this.isFastSearch = false
          }
        }, err => {
          console.log(err)
          this.isSeaching = false
          this.isFastSearch = false
        })
      },
      // 责任机构
      async getShopList() {
        this.shopList = this.orgList
        // const shopList = await sessionStorage.getItem(`shop-${this.clientSelected.corpCode}`)
        // if (shopList) {
        //   const s = JSON.parse(shopList)
        //   this.shopList = s
        // } else {
        //   const params = {
        //     corpCode: this.clientSelected.corpCode
        //   }
        //   const res = await findShopList(params)
        //   this.shopList = res.data
        //   sessionStorage.setItem(`shop-${this.clientSelected.corpCode}`, JSON.stringify(res.data))
        // }
      },
      // 省市区
      async getAreaData(value) {
        const res = await selectAreaCode({ areaCode: value || 0 })
        return res.data
      },
      async getProvinceData() {
        this.provinceList = await this.getAreaData(0)
      },
      async provinceChange() {
        this.temp.provinceName = this.getAreaName(this.temp.province, this.provinceList)
        this.temp.city = ''
        this.temp.area = ''
        this.temp.street = ''
        this.temp.address = ''
        this.cityList = await this.getAreaData(this.temp.province)
        this.clearAddressInfo()
      },
      async cityChange() {
        this.temp.cityName = this.getAreaName(this.temp.city, this.cityList)
        this.temp.area = ''
        this.temp.street = ''
        this.temp.address = ''
        this.areaList = await this.getAreaData(this.temp.city)
        this.clearAddressInfo()
      },
      async areaChange() {
        this.temp.countryName = this.getAreaName(this.temp.area, this.areaList)
        this.temp.street = ''
        this.temp.address = ''
        this.streetList = await this.getAreaData(this.temp.area)
        this.clearAddressInfo()
      },
      async streetChange() {
        this.temp.streetName = this.getAreaName(this.temp.street, this.streetList)
        this.temp.address = ''
        this.clearAddressInfo()
        this.$forceUpdate()
      },
      getAreaName(code, list) {
        const codeItem = list.find(item => item.areaCode === code)
        if (codeItem && codeItem.areaName) return codeItem.areaName
        else return ''
      },
      // 输入建议
      async getAddressSuggestionList(cb) {
        const params = {
          page_num: this.addressInfo.page_num,
          page_size: this.addressInfo.page_size,
          queryString: (this.temp.provinceName || '') + (this.temp.cityName || '') + (this.temp.countryName || '') + this.temp.address,
          city: this.temp.cityName
        }
        const res = await getLocalSearch(params)
        if (res && res.results && res.results.length > 0) {
          let list = []
          list = res.results.map(item => ({
            value: item.name || '',
            location: item.location,
            address: item.address || '',
            adcode: item.adcode || '',
            province: item.province || '',
            city: item.city || '',
            area: item.area || ''
          }))
          if (this.temp.area && this.temp.countryName) {
            list = list.filter(item => (item.area && item.area.includes(this.temp.countryName)) || (item.area === ''))
          }
          if (cb) {
            this.suggestionList = list
            cb(this.suggestionList)
          } else {
            this.$nextTick(() => {
              if (params.page_num > 0) {
                this.suggestionList = this.suggestionList.concat(list)
                this.$refs.suggestionInput.suggestions = this.suggestionList
              }
            })
          }
        } else {
          if (cb) {
            this.$message.error('未匹配到正确地址信息，请重新输入详细地址')
            cb([])
          }
        }
      },
      // 定位
      async location() {
        const params = {
          lng: this.temp.longitude,
          lat: this.temp.latitude,
          address: this.temp.address,
          provinceName: this.temp.provinceName || '',
          cityName: this.temp.cityName || '',
          countryName: this.temp.countryName || '',
          area: this.temp.area || ''
        }
        const res = await this.$refs.geolocation.open(params)
        // 处理详细地址
        this.temp.latitude = res.lat
        this.temp.longitude = res.lng
        this.temp.address = res.address
        this.temp.saveClient = false
        this.temp.isConfirm = true
        this.temp.cityCode = this.temp.city
        this.temp.contact = this.temp.contactName
        const params1 = { ...this.shippingInfoData[0], ...this.clientSelected, ...this.shippingAddress, ...this.temp }
        const res2 = await confirmLonLat({ ...params1 })
        if (res2.status === 200) {
          this.$message.success('经纬度确认成功')
        }
      },
      getLoad() {
        console.log('i am load')
        this.addressInfo.page_num++
        this.$refs.suggestionInput.fetchSuggestions()
      },
      // 获取主营商品价格
      async getGoodsPrices() {
        try {
          const res = await phoneOrderGoodsPrices()
          this.mainGoodsPrices = res.data
        } catch (e) {
          console.log(e)
        }
      },
      // 查询商品楼层费
      async GetFloorfee(params) {
        try {
          const res = await phoneOrderFloorfee(params)
          this.FloorfeeList = res.data
        } catch (e) {
          console.log(e)
        }
      },
      // 查询商品服务费
      async GetServePrice(params) {
        try {
          const res = await phoneOrderServePrice(params)
          this.ServePriceList = res.data
        } catch (e) {
          console.log(e)
        }
      },

      async queryAddressSearch(queryString, cb) {
        // if (!queryString.includes('村')) {
        //   this.$message.warning('详细地址需要包含村或者小区、公交地铁站附近，方便精确计算配送费')
        // }
        const { provinceName, cityName, countryName } = this.temp
        if (queryString !== this.slectAddress.address) {
          this.addressInfo.page_num = 0
        }
        if (
          queryString !== this.shippingInfoSelected.address &&
          queryString !== this.slectAddress.address
        ) {
          this.clearAddressInfo()
        } else {
          if (
            queryString === this.shippingInfoSelected.address &&
            provinceName === this.shippingInfoSelected.provinceName &&
            cityName === this.shippingInfoSelected.cityName &&
            countryName === this.shippingInfoSelected.countryName
          ) {
            this.temp.latitude = this.shippingInfoSelected.latitude
            this.temp.longitude = this.shippingInfoSelected.longitude
          }
          if (
            queryString === this.slectAddress.address &&
            provinceName === this.slectAddress.provinceName &&
            cityName === this.slectAddress.cityName &&
            countryName === this.slectAddress.countryName
          ) {
            this.temp.latitude = this.temp.latitude
            this.temp.longitude = this.temp.longitude
          }
        }
        this.getAddressSuggestionList(cb)
      },
      floorChange() {
        if (this.temp.floor && this.commodityData.length > 0) {
          this.getCommodityData()
        }
      },
      // 地址模糊匹配
      async handleSelect(item) {
        this.clearAddressInfo()
        const latAndLon = item.location
        if (latAndLon && latAndLon.lat && latAndLon.lng) {
          this.temp.latitude = latAndLon.lat
          this.temp.longitude = latAndLon.lng
          this.slectAddress = {
            provinceName: this.temp.provinceName,
            cityName: this.temp.cityName,
            countryName: this.temp.countryName,
            address: this.temp.address
          }
          if (this.temp.orgId) {
            // this.checkAddress()
            if (this.isFirstDepositOrder) {
              this.$refs.placeAnOrder.getDefaultGoodsInfo()
            } else if (this.depositDetailsInfo.isDeliver) {
              const { orgId, orgSNNo, orgName } = await this.getNearestStationInfo()
              if (this.temp.orgId !== orgId) {
                this.temp.orgId = orgId
                this.temp.orgSNNo = orgSNNo
                this.temp.orgName = orgName
                this.shopChange()
              }
            }
          }
          this.getShopDistanceList()
        }
        this.temp.saveClient = false
      },
      // 计算配送距离
      async checkAddress(map) {
        this.showConfirmTip = false
        const org = this.shopList.find(item => item.orgId === this.temp.orgId)
        const params = {
          lng: this.temp.longitude,
          lat: this.temp.latitude,
          orglng: org.lon,
          orglat: org.lat
        }
        const res = await phoneOrderDistance(params)
        if (res && res.data) {
          this.temp.distance = res.data.distance
          if (!map) {
            if (res.data.distance && res.data.distance > 5000) {
              this.showConfirmTip = true
              // this.$confirm('您的配送地址大于5公里,将会产生配送费用,请再次确认或修改。', '提示', {
              //   confirmButtonText: '确定',
              //   cancelButtonText: '取消',
              //   type: 'warning'
              // })
              //   .then(() => {
              //     this.addressConfirm()
              //   })
              //   .catch(() => {
              //     this.$message({
              //       type: 'info',
              //       message: '已取消'
              //     })
              //   })
            }
          } else {
            this.temp.distance = res.data.distance
          }
        }
      },
      async getShopDistanceList() {
        const params = {
          corpSN: this.clientSelected.corpSN,
          longitude: this.temp.longitude,
          latitude: this.temp.latitude
        }
        const res = await findShopDistanceList(params)
        if (res && res.data && res.data.length > 0) {
          const r = res.data.slice(0, 2)
          const distanceInfo = r.map(item => (
            `${item.orgName}-${item.distance}(km)`
          ))
          this.distanceInfo = distanceInfo.join(',')
        }
      },
      async addressConfirm() {
        // if (this.temp.latitude && this.temp.longitude) {
        const params = {
          lng: this.temp.longitude, lat: this.temp.latitude,
          address: this.temp.address,
          provinceName: this.temp.provinceName || '',
          cityName: this.temp.cityName || '',
          countryName: this.temp.countryName || '',
          area: this.temp.area || ''
        }
        const newAddress = await this.$refs.geolocation.open(params)
        this.temp.latitude = newAddress.lat
        this.temp.longitude = newAddress.lng
        this.temp.address = newAddress.address
        const params1 = { ...this.clientSelected, ...this.shippingAddress, ...this.temp }
        const res2 = await confirmLonLat({ ...params1 })
        if (res2.status === 200) {
          this.$message.success('经纬度确认成功')
        }
        this.showConfirmTip = false
        this.temp.isConfirm = 1
        if (this.temp.orgId) {
          this.$refs.placeAnOrder.deliveryCostName = '远距配送费'
          this.$refs.placeAnOrder.commodityData = []
          if (this.isFirstDepositOrder) {
            this.$refs.placeAnOrder.getDefaultGoodsInfo()
          } else if (this.depositDetailsInfo.isDeliver) {
            const { orgId, orgSNNo, orgName } = await this.getNearestStationInfo()
            if (this.temp.orgId !== orgId) {
              this.temp.orgId = orgId
              this.temp.orgSNNo = orgSNNo
              this.temp.orgName = orgName
              this.shopChange()
            }
          }
          // this.checkAddress()
        }
        // } else {
        //   this.$message.warning('请先选择输入建议列表中地址')
        // }
      },
      // 选择机构
      async shopChange() {
        const gTypeId = this.$refs.placeAnOrder.form.gtId
        const goods = this.$refs.placeAnOrder.form.goodsId
        this.temp.orgSNNo = formatColumnMap(this.shopList, 'orgId', this.temp.orgId, 'orgSNNo')
        this.temp.orgName = formatColumnMap(this.shopList, 'orgId', this.temp.orgId, 'orgName')
        if (gTypeId || goods) {
          this.$confirm('变更机构需要重新筛选商品，您确定吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              this.temp.gtId = ''
              this.temp.goodsId = ''
              this.$refs.placeAnOrder.placeAnOrderClear()
              this.$refs.placeAnOrder.getGoodTypeList()
              this.$refs.placeAnOrder.getTimeClear()
              this.$refs.placeAnOrder.gettimeList()
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消'
              })
            })
        } else {
          this.$refs.placeAnOrder.getGoodTypeList()
        }
        this.temp.userId = ''
        this.currentuserInfo = {}
        await this.getUserList()
        if (this.temp.latitude && this.temp.longitude) {
          // this.checkAddress()
        } else {
          this.$message.warning('您选择的地址不正确')
        }
      },

      // 处理人
      async getUserList() {
        if (!this.temp.orgId) {
          return
        }
        // const params = {
        //   corpCode: this.clientSelected.corpCode,
        //   orgId: this.temp.orgId
        // }
        const params = {
          deliveryOrgId: this.temp.orgId,
          deliveryOrgSNNo: this.temp.orgSNNo
        }
        if (this.tabLabel === '报修') {
          this.tempRules.userId[0].required = false
          this.temp.userName = ''
          this.temp.userId = ''
          params.utype = 1 << 27
        }
        // const res = await findUserList(params)
        const res = await csDeliverUserList(params)
        this.handlerList = res.data
        if (this.tabLabel !== '报修') {
          const firstList = []
          const otherList = []
          this.handlerList.forEach((item) => {
            if (item.utype) {
              if ((item.utype & 32768) > 0) {
                firstList.push(item)
              } else {
                otherList.push(item)
              }
            } else {
              otherList.push(item)
            }
          })
          this.handlerList = firstList.concat(otherList)
        }
      },
      async handerChange() {
        this.currentuserInfo = await this.getUserInfo()
        if (this.temp.userId && this.tabLabel === '买气') {
          const res = await orderDutyCheck({ ownerId: this.temp.userId, corpSN: this.currentuserInfo.corpSN })
          if (res.data === 1) {
            const info = this.handlerList.find(item => item.userId === this.temp.userId)
            this.$refs.confirmClasses.open(info)
          }
        }
      },
      async getUserInfo() {
        const userInfo = this.handlerList.find(
          item => item.userId === this.temp.userId
        )
        if (userInfo) {
          this.temp.userName = userInfo.userName
          const { userId, userCode, userName, corpSN } = userInfo
          return { userId, userCode, userName, corpSN }
        }
      },
      // 商品类型变化
      goodTypeChange(e) {
        this.temp.gTypeId = e.gTypeId || ''
      },
      goodsChange(e) {
        this.temp.goods = e.goods || ''
        this.temp.specCode = e.specCode || ''
      },
      clearAddressInfo() {
        this.$refs.placeAnOrder.form.gTypeId = ''
        this.$refs.placeAnOrder.form.goods = ''
        this.temp.latitude = ''
        this.temp.longitude = ''
        this.$refs.placeAnOrder.deliveryCostName = '配送费'
        this.$refs.placeAnOrder.commodityData = []
      },
      // 重置
      resetForm() {
        this.clientData = {
          currentPage: 1,
          pageSize: 10,
          total: 0,
          data: []
        }
        this.record = '1'
        this.temp.provinceName = ''
        this.temp.cityName = ''
        this.temp.countryName = ''
        this.temp.province = ''
        this.temp.city = ''
        this.temp.area = ''
        this.temp.contactName = ''
        this.temp.telephone = ''
        this.temp.address = ''
        this.temp.doorplate = ''
        this.temp.floor = ''
        this.temp.orgName = ''
        this.temp.orgSNNo = ''
        this.temp.orgId = ''
        this.temp.userId = ''
        this.temp.userName = ''
        this.shippingInfoData = []
        this.shippingAddressData = []
        this.shippingPhone = {}
        this.shippingAddress = {}
        this.purchaseHistory = []
        this.complainTableData = []
        this.clientSelected = {}
        this.shippingInfoSelected = {}
        this.currentuserInfo = {}
        this.shopList = []
        this.handlerList = []
        this.distanceInfo = ''
        this.recheckbill = false
      },
      doDelete(row, key) {
        this.$confirm('确定删除该数据吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            if (key === 1) {
              this.handleDelete(row)
            } else {
              this.addressDelete(row)
            }
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            })
          })
      },
      async handleDelete(row) {
        if (this.shippingInfoData.length > 1) {
          const params = {
            // corpSN: row.corpSN,
            csmId: row.csmId,
            csmPhoneId: row.csmPhoneId,
            csmPhone: row.csmPhone,
            isMain: row.isMain
          }
          const res = await deletePhoneByParam(params)
          if (res && res.data) {
            await this.getPhoneList()
            this.getFillShippingInfo()
          }
        } else {
          this.$message.warning('唯一配送信息不允许删除')
        }
      },
      async addressDelete(row) {
        if (this.shippingAddressData.length > 1) {
          const params = {
            // corpSN: row.corpSN,
            csmId: row.csmId,
            csmAddressId: row.csmAddressId
          }
          const res = await deleteAddressByParam(params)
          if (res && res.data) {
            await this.getAddressInfoList()
            this.getFillShippingInfo()
          }
        } else {
          this.$message.warning('唯一配送信息不允许删除')
        }
      },
      // 点击订单号
      async circulationInfo(row) {
        await this.$refs.orderDetails.open(row)
      },
      // 点击催单
      async openPressOrder(row) {
        if (row.transactTime) {
          const n = dayjs(new Date())
          const d = dayjs(row.transactTime)
          const appointmentDt = row.appointmentDt ? dayjs(row.appointmentDt).format('YYYY-MM-DD') : ''
          const today = dayjs(new Date()).format('YYYY-MM-DD')
          const f = n.diff(d, 'minute')
          console.log(n, d, f, '--------------')
          if ((appointmentDt && today && appointmentDt === today)) {
            if (f > 30) { // 预约当天且下单超过30分钟
              this.toPressOrder(row)
            } else {
              this.$message.warning('下单30分钟后才可进行催单！')
            }
          } else {
            if (dayjs(appointmentDt) > dayjs(today)) { // 预约时间不是今天未达到
              this.$message.warning('仅预约当天支持催单!')
            } else { // 预约时间是今天之前
              this.toPressOrder(row)
            }
          }
        }
      },
      async toPressOrder(row) {
        const params = { orderCode: row.orderCode }
        const res = await orderbillCanUrge(params)
        if (res) {
          if (res.data === 1) {
            this.$message.warning('该场站本时间段不支持催单！')
          } else {
            await this.$refs.pressOrder.open({ ...row, billCode: row.orderCode, billType: 1 })
            this.getRecentOrderList()
          }
        }
      },
      // 点击修改
      async changeAppointmentDt(row) {
        await this.$refs.changeAppointmentDt.open(row, this.clientSelected)
      },
      // 刷新三次购气记录
      refresh() {
        this.getRecentOrderList()
      },
      validateForm() {
        this.$refs.form.validate(async valid => {
          if (valid) {
            this.$refs.placeAnOrder.doSubmit()
          }
        })
      },
      onSubmit() {
        this.resetForm()
        this.temp.phone = ''
        this.temp.txt = ''
        this.monthlyBillTips1 = ''
        this.monthlyBillTips2 = ''
        this.tabLabel = '买气'
        this.temp[this.typeVal[this.conditionType - 1]] = ''
        this.$refs['form'].resetFields()
        this.updateData(this.currentPhoneData.title)
        this.depositDetailsInfo = {}
      },
      updateData(activeName) {
        const pbxList = store.state.app.PBXData
        if (pbxList && pbxList.length > 0) {
          const activeIndex = pbxList.findIndex(item => item.p5 === activeName)
          store.state.app.PBXData.splice(activeIndex, 1)
          store.state.app.PBXData[activeIndex] = {
            p5: activeName,
            done: true
          }
        }
      },
      async setUserData() {
        await this.getUserList()
        if (this.tabLabel === '报修') {
          this.temp.orgId = this.clientSelected.nearStation
          this.temp.orgSNNo = formatColumnMap(this.shopList, 'orgId', this.temp.orgId, 'orgSNNo')
          this.temp.userId = ''
          this.$refs.callRepair.resetAppointment()
          this.$refs.callRepair.getAppointmentData(this.temp.orgId)
        } else {
          this.temp.orgId = this.userData.orgId
          this.temp.orgName = formatColumnMap(this.shopList, 'orgId', this.temp.orgId, 'orgName')
          const orgSNNo = this.shopList.filter((item) => {
            return item.orgId === this.temp.orgId
          })
          if (orgSNNo.length > 0) {
            this.temp.orgSNNo = orgSNNo[0].orgSNNo
          }
          this.temp.userId = this.userData.userId
        }
      },
      async tabChange(tab, e) {
        console.log(this.$refs.optionTab)
        this.tabLabel = tab.label
        if (this.tabLabel === '报修' || this.tabLabel === '投诉') {
          this.queryUserByOrgId()
          this.tempRules.orgId[0].required = false
        } else if (this.tabLabel === '退瓶') {
          this.temp.userId = ''
          this.temp.orgId = this.clientSelected.nearStation
          this.temp.orgSNNo = formatColumnMap(this.shopList, 'orgId', this.temp.orgId, 'orgSNNo')
          await this.getUserList()
          this.$refs.returnBottle.depositlist(this.clientSelected, this.shippingAddress)
        } else {
          this.tempRules.orgId[0].required = true
          this.temp.userId = ''
          if (this.clientSelected.corpCode) {
            this.defalutClientData()
          }
        }
        if (this.tabLabel === '投诉') {
          this.$refs.callComplaint.getInitData()
        }
      },
      getCsmInfo() {
        this.csmInfo = {}
        this.saveClient.saveClient = false
        this.csmInfo.csmCode = this.clientSelected.csmCode
        this.csmInfo.csmId = this.clientSelected.csmId
        this.csmInfo.csmName = this.clientSelected.csmName
        this.csmInfo.csmRgPhone = this.temp.telephone
        this.csmInfo.newType = this.clientSelected.newType
        this.csmInfo.subType = this.clientSelected.subType
        var csmAddress = this.temp.address
        this.csmInfo.csmRgAddress = csmAddress
        this.csmInfo.csmAddressId = this.shippingInfoSelected.csmAddressId
        this.csmInfo.sfzh = this.temp.sfzh
        // 地址里有换行符时，此处的比较会有问题，需要把换行符替换掉
        if (this.csmInfo.csmAddressId && (!this.csmInfo.csmRgAddress || csmAddress !== this.csmInfo.csmRgAddress)) {
          this.csmInfo.csmAddressId = 0
          // delete this.csmInfo.insureEndDt
        }
        this.csmInfo.decimalSpare2 = this.$refs.placeAnOrder.cinfo.decimalSpare2 || 0
        this.csmInfo.provinceCode = this.temp.province
        this.csmInfo.provinceName = this.temp.provinceName
        this.csmInfo.cityCode = this.temp.city
        this.csmInfo.cityName = this.temp.cityName
        this.csmInfo.countryCode = this.temp.area
        this.csmInfo.countryName = this.temp.countryName
        this.csmInfo.streetCode = this.temp.street
        this.csmInfo.streetName = this.temp.streetName
        this.csmInfo.csmRgAddress = csmAddress
        this.csmInfo.contact = this.temp.contactName
        this.csmInfo.csmFloor = this.temp.floor
        this.csmInfo.csmType = this.clientSelected.csmType * 1
        this.csmInfo.doorplate = this.temp.doorplate
        this.csmInfo.lat = this.temp.latitude
        this.csmInfo.lon = this.temp.longitude
        if ((this.clientSelected.csmName || '') === '') {
          this.csmInfo.csmName = this.csmInfo.contact
        }
        const orgInfo = this.shopList.filter((item) => {
          return item.orgId === this.temp.orgId
        })
        if (orgInfo) {
          this.csmInfo.orgId = orgInfo[0].orgId
          this.csmInfo.orgName = orgInfo[0].orgName
          this.csmInfo.orgSNNo = orgInfo[0].orgSNNo
        }
        this.csmInfo.remark = this.temp.remark
        // 来源话务下单编辑客户
        this.csmInfo.comeFromEdit = 2
        // 配置相关
        if (!this.clientSelected.csmId && (this.corpSettingData.sp1 >> 5 & 0x01) === 0x01) {
          this.csmInfo.csmStatus = 1
        }
        // this.csmInfo.zzbh = this.temp.zzbh
        this.csmInfo = { ...this.phoneData, ...this.csmInfo }
        return this.csmInfo
      },
      async saveClient() {
        this.$refs.form.validate(async valid => {
          if (valid) {
            this.csmInfo = this.getCsmInfo()
            var params = { ...this.csmInfo }
            // console.log('params', params)
            this.$confirm('您是要修改选中的关联地址还是新增一个新地址?', '提示', {
              confirmButtonText: '新增',
              cancelButtonText: '修改',
              type: 'warning',
              distinguishCancelAndClose: true
            }).then(async() => {
              params.csmAddressId = 0
              // if (this.clientSelected.qrCode) {
              //   this.$confirm('用户已绑定一户一码，确认变更地址吗?', '提示', {
              //     confirmButtonText: '确定',
              //     cancelButtonText: '取消',
              //     type: 'warning'
              //   }).then(async() => {
              //     params.qrCode = this.clientSelected.qrCode
              //     // console.log(params)
              //     const res = await phoneOrderSaveUser(params)
              //     if (res.success) {
              //       this.$message.success('保存成功')
              //       this.temp.saveClient = true
              //     }
              //   })
              //   return
              // }
              const res = await phoneOrderSaveUser(params)
              if (res.success) {
                this.$message.success('保存成功')
                this.temp.saveClient = true
                this.fastSearch()
              }
            }).catch(async(action) => {
              if (action === 'close') {
                return
              }
              if (this.clientSelected.qrCode) {
                this.$confirm('用户已绑定一户一码，确认变更地址吗?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(async() => {
                  params.qrCode = this.clientSelected.qrCode
                  // console.log(params)
                  const res = await phoneOrderSaveUser(params)
                  // console.log(res)
                  if (res.success) {
                    this.$message.success('保存成功')
                    this.temp.saveClient = true
                    this.fastSearch()
                  }
                }).catch(() => {})
                return
              }
              const res = await phoneOrderSaveUser(params)
              if (res.success) {
                this.$message.success('保存成功')
                this.temp.saveClient = true
              }
            })
          } else {
            this.$message.warning('请将必填项填写完毕')
          }
        })
      },
      handleClick() {
        if (this.record === '1') {
          this.getRecentOrderList()
        }
        if (this.record === '2') {
          this.getComplainTop()
        }
      },
      async complainSearch() {
        const complainStatus = await sessionStorage.getItem(`complainStatus_callorder`)
        if (complainStatus) {
          const c = JSON.parse(complainStatus)
          this.complainStatus = c
        } else {
          const res = await getComplainStatus()
          this.complainStatus = res.data
          await sessionStorage.setItem(`complainStatus_callorder`, JSON.stringify(this.complainStatus))
        }
      },
      async getComplainTop() {
        if (!this.clientSelected.corpSN && !this.clientSelected.csmId) return
        this.complainTableData = []
        if (this.clientSelected.csmId) {
          const params = {
            csmId: this.clientSelected.csmId,
            topCount: 3,
            corpSN: this.clientSelected.corpSN
          }
          const res = await complainTop(params)
          if (res.data) {
            this.complainTableData = res.data
            this.complainTableData.forEach((item) => {
              const status = this.complainStatus.filter((item2) => {
                return item2.value === item.cstatus
              })
              if (status.length > 0) {
                item.statusName = status[0].desc
              }
              item.createTime = item.createTime ? parseTime(item.createTime) : ''
              item.createTime = item.createTime ? dayjs(item.createTime).format('YY-MM-DD HH:mm') : ''
            })
          }
        }
      },
      // 催单
      async handleReminder(row) {
        await this.$refs.reminderDialog.open(row)
      },
      // 退单
      async handleChargeback(row) {
        await this.$refs.chargebackDialog.open(row)
      },
      // 流转
      async handleExchange(row) {
        await this.$refs.exchangeDialog.open(row, 'complaint')
      },
      chargebackSubmit() {
        if (this.record === '2') {
          this.getComplainTop()
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
.phone-search {
  display: flex;
  justify-content: space-between;
  padding: 18px 20px 0 20px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  .callTime {
    padding-top: 10px;
  }
}
.bottom-margin {
  margin-bottom: 10px;
}
.conditionType {
  display: flex;
  margin-bottom: 10px;
  & /deep/ .el-form-item__label {
    min-width: 82px;
  }
}
.conditionType-btn {
  margin-bottom: 10px;
}
.type-selecte {
  width: 100px;
}
.card {
  border-radius: 8px;
  & /deep/ .el-card__header {
    padding-bottom: 10px;
    padding-left: 10px;
    font-size: 14px;
    font-weight: bold;
  }
  & /deep/ .el-card__body {
    padding: 10px;
  }
  .shipping-address {
    display: flex;
  }
  .tips {
    display: block;
    margin-bottom: 10px;
    font-size: 14px;
    font-weight: 400;
    color: #999;
  }
  .detailBtn {
    float: right;
    padding: 0 0;
  }
}

.client {
  display: flex;
  margin-bottom: 10px;
  .client-item {
    div {
      display: flex;
      flex-wrap: wrap;
      margin-bottom: 10px;
      span {
        display: block;
      }
      span:nth-child(1) {
        min-width: 80px;
      }
      span:nth-child(2) {
        min-width: 120px;
      }
    }
    div:nth-last-child(1) {
      margin-bottom: 0;
    }
  }
  .client-item:nth-child(1) {
    margin-right: 20px;
    margin-bottom: 10px;
  }
}
.client-content {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  margin-bottom: 10px;
  .client-row {
    display: flex;
    width: 33%;
    margin-bottom: 10px;
    .client-label {
      width: 80px;
    }
    .client-label2 {
      width: 115px;
    }
    .client-value {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
.select-radio {
  & /deep/ .el-radio__label {
    display: none;
  }
}

.shipping {
  min-height: 282px;
  .el-form-item {
    display: flex;
    // margin-bottom: 10px;
    &/deep/ .el-form-item__label {
      width: 85px;
      min-width: 85px;
    }
  }

  .col-input-full {
    &/deep/ .el-form-item__content {
      width: 100%;

      .el-autocomplete,
      .el-select,
      .el-input-number {
        width: 100%;
      }
    }
  }
  .concat-address {
    & /deep/ .el-form-item__content {
      display: flex;
      .el-button--primary {
        margin-left: 8px;
      }
    }
  }
  .doorplate-floor {
    &/deep/ .el-form-item__label {
      width: 70px;
      min-width: 70px;
    }
  }

  .floor {
    & /deep/ .el-input {
      input {
        text-align: left;
      }
    }
  }

  .costormLabel {
    .el-select {
      width: 24.3%;
    }
  }
  .redlabel {
    &/deep/ .el-form-item__label {
      &::before {
        margin-right: 4px;
        color: #f56c6c;
        content: "*";
      }
    }
  }
}

.option-tab {
  & /deep/ .el-tabs__header {
    border-bottom: none;
  }

  & /deep/ .el-tabs__nav-wrap {
    background-color: #fff;
    .el-tabs__nav-scroll {
      .el-tabs__nav {
        .el-tabs__item {
          height: 50px;
          min-width: 100px;
          font-size: 16px;
          font-weight: bold;
          line-height: 50px;
          text-align: center;
        }
        .is-active {
          border-right-color: $themeColor;
        }
      }
    }
  }
}
.option-tab-show {
  overflow: visible;
  & /deep/ .el-tabs__content {
    overflow: visible;
  }
}
.address-autocomplete {
  li {
    padding: 7px;
    line-height: normal;
    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }
  }
}

.confirm-tip,
.confirm-distance {
  position: relative;
  top: -15px;
  left: 0;
  margin-left: 85px;
  font-size: 12px;
  line-height: 1;
  color: #F56C6C;
}
.confirm-distance {
  top: -6px;
}
.order-code {
  color: $themeColor !important;
  text-decoration: underline;
  cursor: pointer;
}
/deep/.el-form-item__label {
  display: inline-block;
  float: none;
  padding: 0 12px 0 0 !important;
}
.saveClient {
  display: flex;
  justify-content: flex-end;
}
.link {
  color: #01999F;
  cursor: pointer;
}
.red {
  color: #F56C6C;
}
</style>
